package com.xbongbong.pro.statistic.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.paas.constant.BiConstant;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.BiRelTableEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsInitVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.domain.dao.ChartCustomDao;
import com.xbongbong.pro.domain.entity.ChartEntity;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.BiErrorCodeEnum;
import com.xbongbong.pro.statistic.enums.ChartTypeEnum;
import com.xbongbong.pro.statistic.help.CustomHelp;
import com.xbongbong.pro.statistic.model.ChartCustomModel;
import com.xbongbong.pro.statistic.pojo.dto.MappingInitDTO;
import com.xbongbong.pro.statistic.pojo.dto.TransChartDTO;
import com.xbongbong.pro.statistic.service.ChartCustomService;
import com.xbongbong.pro.statistic.service.ChartScriptService;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.nio.entity.NStringEntity;
import org.elasticsearch.client.RestClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
@Service("chartScriptService")
public class ChartScriptServiceImpl implements ChartScriptService {
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private ChartCustomModel chartCustomModel;
    @Resource
    private CustomHelp customHelp;
    
    private static final Logger LOG = LoggerFactory.getLogger(ChartScriptServiceImpl.class);
    @Override
    public PaasFormDataEsInitVO addAllAlias(MappingInitDTO mappingInitDTO) throws XbbException {
        PaasFormDataEsInitVO dataInitVO = new PaasFormDataEsInitVO();
        HttpEntity httpEntity = null;
        try {
            JSONArray jsonArray = new JSONArray();
            for (BiRelTableEnum biRelTableEnum : BiRelTableEnum.values()) {
                try {
                    if(IndexTypeEnum.UNKNOWN.getCode().equals(biRelTableEnum.getCode())){
                        continue;
                    }
                    String index = biRelTableEnum.getIndex();
                    String alias = index.replace(BiConstant.INDEX_SUFFIX,"");
                    JSONObject addJson = JSONObject.parseObject(" {\"actions\": [{\"add\":{\"index\":\"" + index + "\",\"alias\":\"" + alias + "\"}}]}");
                    httpEntity = new NStringEntity(JSON.toJSONString(addJson, SerializerFeature.DisableCircularReferenceDetect), ContentType.APPLICATION_JSON);
                    RestClient restClient = xbbElasticsearchRestTemplate.getRestClient(biRelTableEnum.getIndex());
//                    Response response = restClient.performRequest("POST", "/_aliases", Collections.emptyMap(), httpEntity);
                } catch (Exception e) {
                    LOG.error("",e);
                }
//                jsonArray.add(addJson);
            }
//            LOG.info("========="+jsonArray.toString());
//            RestClient restClient = xbbElasticsearchRestTemplate.getRestClient(BiRelTableEnum.IDX_STATISTIC_CONTRACT.getIndex());
//            Response response = restClient.performRequest("POST", "/_aliases", Collections.emptyMap(), httpEntity);
        }  catch (Exception e) {
            LOG.error("",e);
            throw  new XbbException(BiErrorCodeEnum.API_ERROR_241011);
        } finally {
            if (Objects.nonNull(httpEntity)) {
                try {
                    ((NStringEntity) httpEntity).close();
                } catch (Exception e) {
                    LOG.error("",e);
                }
            }
        }
        return dataInitVO;
    }

    @Override
    public void repairOriginalAttr(TransChartDTO transChartDTO) throws XbbException {
        LocaleContextHolder.setLocale(Locale.CHINA);
        long start = DateTimeUtil.getInt();

        // 查询在使用的多表双轴图
        Map<String, Object> params = new HashMap<>(16);
        params.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        params.put("muti", 0);
        params.put("chartType", ChartTypeEnum.BIAXIAL_CHART.getCode());
        List<ChartEntity> chartEntityList = chartCustomModel.findEntitys(params);
        LOG.warn("共" + chartEntityList.size() + "条数据");
        for (int j = 0, chartEntityListSize = chartEntityList.size(); j < chartEntityListSize; j++) {
            ChartEntity chartEntity = chartEntityList.get(j);
            Integer chartType = chartEntity.getChartType();
            // 待处理值
            JSONArray valArr;
            if (Objects.equals(chartType, ChartTypeEnum.SECOND_TARGET_CHART.getCode())) {
                valArr = chartEntity.getSecondTargetAttr();
            } else {
                valArr = chartEntity.getChartValueSecond();
            }
            if (CollectionsUtil.isEmpty(valArr)) {
                LOG.warn("第" + (j + 1) + "条数据不用刷");
                continue;
            }
            JSONObject formIdAttr = chartEntity.getFormIdAttr();
            if (formIdAttr == null) {
                LOG.warn("第" + (j + 1) + "条数据不用刷");
                continue;
            }
            for (int i = 0; i < valArr.size(); i++) {
                String originalAttr;
                JSONObject valObj = valArr.getJSONObject(i);
                String attr = FastJsonHelper.getStringOrDefault(valObj, "attr", "");
                String formId = FastJsonHelper.getStringOrDefault(valObj, "formId", "");
                JSONObject formObj = formIdAttr.getJSONObject(formId);
                if (Objects.nonNull(formObj)) {
                    // 先查有没有映射值
                    originalAttr = formObj.getString(attr);
                    if (StringUtil.isEmpty(originalAttr)) {
                        // 为空，没拿到，走一遍逻辑从新生成
                        customHelp.setOriginalAttr(chartEntity, false);
                        break;
                    } else {
                        valObj.put("originalAttr", originalAttr);
                    }
                }
            }
            // 更新
            chartCustomModel.update(chartEntity);
            LOG.warn("第" + (j + 1) + "条数据刷完");
        }
        LOG.warn("consume:{}", (DateTimeUtil.getInt() - start));
    }


}
